import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { GetCookieTOOL } from '@utils/index';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/overview',
    component: () => import('@/components/Home'),
    children: [
      {
        path: '/overview',
        name: 'overview',
        component: () => import('@/components/overview'),
      },
      {
        path: '/overview/iurCarrier',
        name: 'iurCarrier',
        component: () => import('@/components/overview/iurCarrier'),
      },
      {
        path: '/overview/qualificationDetail',
        name: 'qualificationDetail',
        component: () => import('@/components/overview/qualificationDetail'),
      },
      {
        path: '/industryView',
        name: 'industryView',
        component: () => import('@/components/industryView'),
      },

      {
        path: '/industryView/company/:company_id',
        name: 'industryView_company',
        component: () => import('@/components/insight/companyDetail'),
      },
      {
        path: '/insight',
        name: 'insight',
        component: () => import('@/components/insight'),
      },
      {
        path: '/insight/company/:company_id',
        name: 'insight_company',
        component: () => import('@/components/insight/companyDetail'),
      },
    ],
  },
  {
    path: '/admin',
    name: 'admin',
    component: () => import('@/components/admin'),
  },
  {
    path: '/loginAdmin',
    name: 'loginAdmin',
    component: () => import('@/components/common/loginAdmin'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/components/common/login'),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

const viewArr = [
  'overview',
  'iurCarrier',
  'qualificationDetail',
  'industryView',
  'industryView_company',
  'insight',
  'insight_company',
];

router.beforeEach((to: any, _: any, next: any) => {
  next();
  const isLoginAdmin = GetCookieTOOL('userAdmin');
  const isLogin = GetCookieTOOL('user');
  if (to.matched.length === 0) {
    _.path ? next({ path: _.path }) : next('');
  } else {
    if (viewArr.includes(to.name) || to.path === '/') {
      // 这里是后台管理用户或前台展示密码二选一，两个有其中一个就能进入页面
      if (!isLogin) {
        next({
          name: 'login',
        });
      } else {
        next();
      }
    } else if (to.name === 'admin') {
      if (!isLoginAdmin) {
        next({
          name: 'loginAdmin',
        });
      } else {
        next();
      }
    } else {
      if (to.path === '/login') {
        // 这里也是同理，两种cookie取其中一个就行
        isLogin ? next({ path: _.path }) : next();
      } else if (to.path === '/loginAdmin') {
        isLoginAdmin ? next({ path: '/admin' }) : next();
      } else {
        next();
      }
      next();
    }
  }
});

export default router;
